package com.ruoyi.web.controller.oper;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.oper.domain.*;
import com.ruoyi.oper.service.IOperCartService;
import com.ruoyi.oper.service.IOperPersonService;
import com.ruoyi.oper.service.IOperProductService;
import com.ruoyi.oper.service.impl.OperPersonServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/oper/cart")
public class OperCartController extends BaseController {
    @Autowired
    private IOperCartService operCartService;

    @Autowired
    private IOperProductService operProductService;

    @PostMapping("/insert")
    public boolean insertCart(@RequestBody OperCart operCart) {
        boolean flag = true;
        List<OperCart> operCartList = operCartService.selectOperCartList(operCart);
        for (OperCart oc : operCartList) {
            if (oc.getProductId() == operCart.getProductId() && oc.getYanseId() == operCart.getYanseId() && oc.getChimaId() == operCart.getChimaId()) {
                oc.setProCount(oc.getProCount() + operCart.getProCount());
                operCartService.updateOperCart(oc);
                flag = false;
                break;
            }
        }
        if (flag == true) {
            operCartService.insertOperCart(operCart);
        }
        return true;
    }

    @GetMapping("/get_oper_cart_list")
    public OperCartItem getOperCartList(OperCart operCart) {
        List<OperCart> operCartList = operCartService.selectOperCartList(operCart);
        List<OperCartVO> operCartVOList = new ArrayList<>();
        OperCartItem operCartItem = null;
        if (operCartList != null && operCartList.size() > 0) {
            for (OperCart oc : operCartList) {
                OperProduct op = operProductService.selectProductById(oc.getProductId());
                OperYanse oy = operProductService.selectYanseById(oc.getYanseId());
                OperChima oa = operProductService.selectChimaById(oc.getChimaId());
                OperCartVO operCartVO = new OperCartVO(op, oy, oa, oc);
                operCartVOList.add(operCartVO);
            }
            Integer total = 0;
            for (OperCartVO oc : operCartVOList) {
                total = total + Integer.parseInt(oc.getPrice()) * oc.getProCount();
            }
            operCartItem = new OperCartItem();
            operCartItem.setOperCartVOList(operCartVOList);
            operCartItem.setTotal(total);
        }
        return operCartItem;
    }

    @GetMapping("/delete_cart")
    public int deleteCart(Integer id) {
        int del = operCartService.deleteOperCartById(id);
        return del;
    }
}
